<template>
	<view class="box">
		<view class="nav">

			<text @click="comprehensive">综合排序</text>
			<text @click="setsales">销量</text>
			<view class="wprice">
				<text @click="setsort">价格</text>
				<view class="price">
					<image v-if="sort=='asc'|| sort==''" class="img" src="../../static/icon-caret-top.svg"></image>
					<image v-if="sort=='desc' || sort==''" class="img" src="../../static/icon-caret-down.svg"></image>
				</view>
			</view>
			<image class="img1" src="../../static/shop.svg" alt="" />
		</view>
		<view class="container">
			<view :id="`cont_${index + 1}`" class="cont-box"
				:style="{ width: widthCalc, 'margin-left': index === 0 ? 0 : marginCalc }"
				v-for="(numVal, index) in flowData.column" :key="numVal">
				<view class="item-box" @click="navigate(item)" v-for="(item, j) in flowData[`column_${index + 1}`]"
					:key="j">
					<image class="img-tip" :src="item.imgurl" mode="widthFix" lazy-load @load="imgLoad(item)"
						@error="imgError(item)" />
					<view class="tit-tip multi-line-omit">{{ item.name }}</view>
					<view class="desc-tip multi-line-omit"><text :style="{color: 'red'}">满38减3</text> <text
							:style="{color: '#52ED7C'}">先用后付</text></view>
					<view class="desc-tip multi-line-omit"><text class="cololr">￥{{item.price}}券后价</text>
						<text>已售{{ item.sales }}+</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { onMounted, ref, getCurrentInstance, computed, reactive } from 'vue';
	interface shopType {
		_id : string,
		name : string,
		price : number,
		num : number,
		imgurl : string,
		inventory : number,
	};
	let sales = ref('')
	let sort = ref('')
	let shopData = ref<shopType[]>([])
	const _this = getCurrentInstance();
	let flowData = reactive({
		list: [], // 数据值
		column: 2, // 瀑布列数
		columnSpace: 2 // 瀑布列宽间距
	});
	/* 数据赋值 */
	flowData.list = [
		{
			imgUrl: "https://www.logosc.cn/uploads/resources/2023/03/17/1679045108_thumb.jpg",
			title: "自动驾驶汽车对交通和城市规划的未来影响与挑战",
			desc: "分析自动驾驶汽车对未来交通和城市规划的潜在影响，探讨相关挑战。"
		},


	];
	let setsales = () => {
		sales.value = 'true'
		sort.value = ''
		getShop()
	}
	let comprehensive = () => {
		sales.value = ''
		sort.value = ''
		getShop()
	}
	let setsort = () => {
		sales.value = ''
		if (sort.value == '' || sort.value == 'desc') {
			sort.value = 'asc'
			getShop()
		}
		else {
			sort.value = 'desc'
			getShop()
		}
	}
	let navigate = (data : any) => {

		uni.navigateTo({
			url: `/pages/details/details?id=` + data._id
		})
	}
	/* 初始化每一列的数据 */
	for (let i = 1; i <= flowData.column; i++) {
		flowData[`column_${i}`] = [];
	}
	/* 生命周期函数-实例被挂载后调用 */
	onMounted(() => {
		getShop()
	});
	/* 计算列宽 */
	const widthCalc = computed(() => {
		return `${100 / flowData.column - flowData.columnSpace}%`;
	});
	/* 计算 margin 外边距 */
	const marginCalc = computed(() => {
		const columnWidth = 100 / flowData.column - flowData.columnSpace;
		return `${(100 - columnWidth.toFixed(5) * flowData.column) / (flowData.column - 1)}%`;
	});
	/* 获取最小值的对象 */
	const getMinObj = (a, s) => {
		let m = a[0][s];
		let mo = a[0];
		for (let i = a.length - 1; i >= 0; i--) {
			if (a[i][s] < m) m = a[i][s];
		}
		mo = a.filter(i => i[s] === m);
		return mo[0];
	};
	/* 计算每列的高度 */
	function getMinColumnHeight() {
		return new Promise(resolve => {
			const heightArr = [];
			for (let i = 1; i <= flowData.column; i++) {
				uni
					.createSelectorQuery()
					.in(_this)
					.select(`#cont_${i}`)
					.boundingClientRect(res => {
						heightArr.push({ column: i, height: res.height });
					})
					.exec(() => {
						if (flowData.column <= heightArr.length) {
							resolve(getMinObj(heightArr, "height"));
						}
					});
			}
		});
	}
	/* 初始化瀑布流数据 */
	async function initValue(i : number) {


		if (i >= shopData.value.length) return false;

		const minHeightRes = await getMinColumnHeight();
		flowData[`column_${minHeightRes.column}`].push({
			...shopData.value[i],
			index: i
		});
	}
	/* 图片加载完成 */
	function imgLoad(item) {
		const i = item.index;
		initValue(i + 1); // 加载下一条数据
	}
	/* 图片加载失败 */
	function imgError(item) {
		const i = item.index;
		initValue(i + 1); // 加载下一条数据
	}
	let getShop = () => {
		uni.request({
			url: 'http://127.0.0.1:3000/xaw/getshop',
			method: 'GET',
			data: { sales: sales.value, sort: sort.value },
			success(res : any) {
				for (let i = 1; i <= flowData.column; i++) {
					flowData[`column_${i}`] = [];
				}
				shopData.value = res.data.data
				initValue(0);
			}
		})
	}
</script>

<style lang="scss" scoped>
	.box {
		width: 750rpx;

		.container {
			padding: 20rpx;

			.cont-box {
				$borderRadius: 12rpx;
				float: left;


				.item-box {
					width: 100%;
					padding-bottom: 20rpx;
					margin-bottom: 30rpx;
					border-radius: $borderRadius;
					box-shadow: 0rpx 3rpx 6rpx rgba(0, 46, 37, 0.08);

					.img-tip {
						width: 100%;
						border-radius: $borderRadius $borderRadius 0 0;
					}

					.tit-tip {
						text-align: justify;
						font-size: 30rpx;
						padding: 10rpx 20rpx 0;
						font-weight: 900;
					}

					.desc-tip {
						text-align: justify;
						font-size: 26rpx;
						padding: 5rpx 20rpx 0;
						margin-top: 10rpx;
					}
				}
			}
		}

		/* 多行省略 */
		.multi-line-omit {
			word-break: break-all; // 允许单词内自动换行，如果一个单词很长的话
			text-overflow: ellipsis; // 溢出用省略号显示
			overflow: hidden; // 超出的文本隐藏
			display: -webkit-box; // 作为弹性伸缩盒子模型显示
			-webkit-line-clamp: 2; // 显示的行
			-webkit-box-orient: vertical; // 设置伸缩盒子的子元素排列方式--从上到下垂直排列
		}

		/* 单行省略 */
		.one-line-omit {
			width: 100%; // 宽度100%：1vw等于视口宽度的1%；1vh等于视口高度的1%
			white-space: nowrap; // 溢出不换行
			overflow: hidden; // 超出的文本隐藏
			text-overflow: ellipsis; // 溢出用省略号显示
		}

		.cololr {
			color: red;
		}

		.nav {
			border-top: 1px solid #ccc;
			width: 750rpx;
			height: 100rpx;
			background-color: salmon;
			display: flex;
			align-items: center;
			justify-content: space-around;

			.img1 {
				width: 50rpx;
				height: 50rpx;
			}

			.wprice {
				display: flex;
				align-items: center;

				.price {
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: space-evenly;

					.img {
						width: 20rpx;
						height: 20rpx;
					}
				}
			}
		}
	}
</style>